package com.pinyougou.shop.controller;

import org.apache.commons.io.FilenameUtils;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
public class UploadController
{
    //注入文件服务器访问地址
    @Value("${fileServerUrl}")
    private String fileServerUrl;
    //文件上传
    @PostMapping("/upload")
    public Map<String,Object> upload(@RequestParam("file") MultipartFile multiPartFile)
    {
        Map<String,Object> data=new HashMap<>();
        data.put("status",500);

        try
        {
            //加载配置文件
            String conf_filename = this.getClass().getResource("/fastdfs_cilent.conf").getPath();
            //初始化客户端全局对象
            ClientGlobal.init(conf_filename);
            //创建客户端全局对象
            StorageClient storageClient=new StorageClient();
            //获取原文件名
            String originalFilename = multiPartFile.getOriginalFilename();
            //上传文件到 fastDFS 服务器
            String[] urlArr = storageClient.upload_file(multiPartFile.getBytes(), FilenameUtils.getExtension(originalFilename), null);
            //拼接返回的 url 和 ip 地址，拼接成完整的 url
            StringBuffer url= new StringBuffer(fileServerUrl);
            for (String s : urlArr)
            {
                url.append("/"+s);
            }

            data.put("status",200);
            data.put("url",url.toString());
            //System.out.println("返回前端的url = " + url);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return data;
    }
}